package org.kzwl.service.app.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Param;
import org.kzwl.comm.advice.BizException;
import org.kzwl.comm.pojo.bo.book.BooksBasicBO;
import org.kzwl.comm.pojo.dto.book.BookCategoryDTO;
import org.kzwl.comm.pojo.dto.book.MyBooksDTO;
import org.kzwl.comm.pojo.dto.book.MyBooksItem;
import org.kzwl.comm.utils.MyUtils;
import org.kzwl.entity.app.BookUser;
import org.kzwl.entity.app.User;
import org.kzwl.mapper.app.BookUserMapper;
import org.kzwl.mapper.app.UserMapper;
import org.kzwl.service.app.BookUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 张国伟/郭家恒
 * @since 2020-09-10
 */
@Service
public class BookUserServiceImpl extends ServiceImpl<BookUserMapper, BookUser> implements BookUserService {

    @Autowired
    private BookUserMapper bookUserMapper;

    @Autowired
    private UserMapper userMapper;

    //region 加入书架
    @Override
    public void addMyBooks(BooksBasicBO bo) {
        QueryWrapper<BookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BookUser::getCuUserId, bo.getCuUserId()).eq(BookUser::getCuBookId, bo.getCuBookId()).last(" limit 1");
        BookUser result = bookUserMapper.selectOne(queryWrapper);
        if (result != null) {
            if (result.getCuBookUserIsShow() == 0) {
                result.setCuBookUserIsShow(1);
                bookUserMapper.updateById(result);
            } else {
                throw new BizException("此书已经在书架中");
            }
        } else {
            BookUser bookUser = new BookUser();
            bookUser.setCuUserId(bo.getCuUserId());
            bookUser.setCuBookId(bo.getCuBookId());
            bookUser.setCuBookUserIsShow(1);
            bookUserMapper.insert(bookUser);
        }
    }
    //endregion

    //region 查询我的书架
    @Override
    public MyBooksDTO myBooks(BooksBasicBO bo) {
        bo.setCurrent((bo.getCurrent() - 1) * bo.getSize());
        List<MyBooksItem> list = bookUserMapper.queryBooksItem(bo);
        list.forEach(l -> {
            if (l.getCuBookUserContinue().compareTo(new BigDecimal(0)) == 0) {
                l.setCuBookUserPercentage(new BigDecimal(0));
            } else {
                BigDecimal bigDecimal = (l.getCuBookUserContinue().divide(l.getCuBookPages(), 2, BigDecimal.ROUND_HALF_UP));
                l.setCuBookUserPercentage(bigDecimal.multiply(new BigDecimal(100)));
            }

        });
        MyBooksDTO dto = new MyBooksDTO();
        dto.setMyBooksItemList(list);
        if (list != null && list.size() > 0) {
            dto.setMyBooksItem(list.get(0));
            if (dto.getMyBooksItem() != null) {
                List<BookCategoryDTO> categoryDTO = MyUtils.getCategoryDTO(dto.getMyBooksItem().getCuBookAddress());
                if (categoryDTO != null && categoryDTO.size() > 0) {
                    BookCategoryDTO first = categoryDTO.stream().filter(c -> c.getCuBookContinue() >= Integer.parseInt(dto.getMyBooksItem().getCuBookUserContinue() + "")).findFirst().get();
                    if (first != null) {
                        dto.getMyBooksItem().setPrevious(first.getCuBookCategoryName());
                    }
                }
            }
        }
        return dto;
    }
    //endregion

    //region 上次阅读
    @Override
    public MyBooksDTO getPrevious(BooksBasicBO bo) {
        bo.setCurrent(0);
        bo.setSize(1);
        List<MyBooksItem> list = bookUserMapper.queryBooksItem(bo);
        MyBooksDTO dto = new MyBooksDTO();
        dto.setMyBooksItemList(list);
        if (list != null && list.size() > 0) {
            dto.setMyBooksItem(list.get(0));
            List<BookCategoryDTO> categoryDTO = MyUtils.getCategoryDTO(dto.getMyBooksItem().getCuBookAddress());
            if (categoryDTO != null && categoryDTO.size() > 0) {
                BookCategoryDTO first = categoryDTO.stream().filter(c -> c.getCuBookContinue() >= Integer.parseInt(dto.getMyBooksItem().getCuBookUserContinue() + "")).findFirst().get();
                dto.getMyBooksItem().setPrevious(first.getCuBookCategoryName());
            }
        }
        return dto;
    }
    //endregion

    //region 更新阅读页数
    @Override
    public void updateContinue(BooksBasicBO bo) {
        QueryWrapper<BookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BookUser::getCuUserId, bo.getCuUserId()).eq(BookUser::getCuBookId, bo.getCuBookId()).last(" limit 1");
        BookUser result = bookUserMapper.selectOne(queryWrapper);
        if (result == null) {
            BookUser bookUser = new BookUser();
            bookUser.setCuUserId(bo.getCuUserId());
            bookUser.setCuBookId(bo.getCuBookId());
            bookUser.setCuBookUserContinue(bo.getCuBookUserContinue());
            bookUserMapper.insert(bookUser);
        } else {
            result.setCuBookUserContinue(bo.getCuBookUserContinue());
            System.out.println(result.toString());
            bookUserMapper.updateById(result);
        }

        if (bo.getCuUserDayMinute() == null) {
            User user = userMapper.selectById(bo.getCuUserId());
            //如果没有最后一次的日期，也就是第一次看书
            if (user.getCuUserMinuteLast() == null) {
                //累加连续读书天数
                user.setCuUserReadDay(user.getCuUserReadDay() + 1);
            } else {
                //否则，开始判断上一次读书是啥时候
                //时间紧，暂时如此处理。
                String last = user.getCuUserMinuteLast().toString();
                String t = last.substring(0, last.indexOf("T"));
                String s = LocalDateTime.now().toString();
                s = last.substring(0, s.indexOf("T"));
                //如果不是同一天
                if (!s.equals(t)) {
                    //累加读书天数
                    user.setCuUserReadDay(user.getCuUserReadDay() + 1);
                }
            }
            //累加今日读书时长
            user.setCuUserDayMinute(user.getCuUserDayMinute() + bo.getCuUserDayMinute());
            //累加总阅读时长
            user.setCuUserReadHour(user.getCuUserReadHour().add(new BigDecimal(bo.getCuUserDayMinute())));
            //更新最后一次读书为当前时间
            user.setCuUserMinuteLast(LocalDateTime.now());
            userMapper.syncDate(user);
        }
    }
    //endregion

    //region 取消收藏
    @Override
    public void removeMyBooks(BooksBasicBO bo) {
        QueryWrapper<BookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BookUser::getCuUserId, bo.getCuUserId()).eq(BookUser::getCuBookId, bo.getCuBookId()).last(" limit 1");
        BookUser result = bookUserMapper.selectOne(queryWrapper);
        if (result == null) {
            throw new BizException("未找到收藏记录");
        }
        result.setCuBookUserIsShow(0);
        bookUserMapper.updateById(result);
    }
    //endregion

    //region 我的书架 By web
    @Override
    public IPage<MyBooksItem> myBooksByWeb(BooksBasicBO bo) {
        MyBooksDTO previous = this.myBooks(bo);
        IPage<MyBooksItem> page = new Page<>();
        page.setRecords(previous.getMyBooksItemList());
        QueryWrapper<BookUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BookUser::getCuUserId, bo.getCuUserId()).eq(bo.getCuBookUserIsShow() != null, BookUser::getCuBookUserIsShow, bo.getCuBookUserIsShow());
        Integer integer = bookUserMapper.selectCount(queryWrapper);
        page.setTotal(integer);
        return page;
    }
    //endregion

}
